const db = require('../db/config');
const { sqlQueryTableDatasAll, sqlQueryTableDatas } = require('../db/sql');
const { ServerResponseResult } = require('../utils/result');
const { selectDatas, fifterSearchData } = require('../utils/tools');

module.exports.searchActionHandler = function (req, res) {
    const cityId = Number(req.body.cityId),
        keyword = req.body.keyword,
        delayTime = 50;

    const responseResult = new ServerResponseResult();

    if (cityId !== 0) {
        // 查询food数据
        selectDatas(responseResult, sqlQueryTableDatas('food'), 'foodDatas', [cityId]);
        // 查询hotel数据
        selectDatas(responseResult, sqlQueryTableDatas('hotel'), 'hotelDatas', [cityId]);
        // 查询view数据
        selectDatas(responseResult, sqlQueryTableDatas('view'), 'viewDatas', [cityId]);
        // 查询ktv数据
        selectDatas(responseResult, sqlQueryTableDatas('ktv'), 'ktvDatas', [cityId]);
        // 查询massage数据
        selectDatas(responseResult, sqlQueryTableDatas('massage'), 'massageDatas', [cityId]);
    } else {
        // 查询food数据
        selectDatas(responseResult, sqlQueryTableDatasAll('food'), 'foodDatas', [cityId]);
        // 查询hotel数据
        selectDatas(responseResult, sqlQueryTableDatasAll('hotel'), 'hotelDatas', [cityId]);
        // 查询view数据
        selectDatas(responseResult, sqlQueryTableDatasAll('view'), 'viewDatas', [cityId]);
        // 查询ktv数据
        selectDatas(responseResult, sqlQueryTableDatasAll('ktv'), 'ktvDatas', [cityId]);
        // 查询massage数据
        selectDatas(responseResult, sqlQueryTableDatasAll('massage'), 'massageDatas', [cityId]);
    }

    setTimeout(function () {
        // 根据关键字进行数据过滤
        responseResult.foodDatas = fifterSearchData(responseResult.foodDatas, keyword);
        responseResult.hotelDatas = fifterSearchData(responseResult.hotelDatas, keyword);
        responseResult.viewDatas = fifterSearchData(responseResult.viewDatas, keyword);
        responseResult.massageDatas = fifterSearchData(responseResult.massageDatas, keyword);
        responseResult.ktvDatas = fifterSearchData(responseResult.ktvDatas, keyword);

        if (responseResult.foodDatas.length > 0 ||
            responseResult.hotelDatas.length > 0 ||
            responseResult.massageDatas.length > 0 ||
            responseResult.ktvDatas.length > 0 ||
            responseResult.viewDatas.length > 0) {
            responseResult.statusText = 'ok'
        } else {
            responseResult.statusText = 'No Datas'
        }

        return res.send(responseResult);
    }, delayTime);
}